package team.yidong.fenda.wx.controller;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import team.yidong.fenda.payUtil.*;
import team.yidong.fenda.service.GuahaoHistoryService;
import team.yidong.fenda.utils.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by xuanlong on 2018/3/21.
 */
@Controller
public class WxGuahaoHistoryController {
    @Autowired
    GuahaoHistoryService guahaoHistoryService;
    @Autowired
    WxPrePayUtil wxPrePayUtil;
    @Autowired
    WxLoginUtil wxLoginUtil;
    @Autowired
    GuahaoPayUtil guahaoPayUtil;
    @Autowired
    FalvGuahaoPayUtil falvGuahaoPayUtil;

    /**
     * 医院挂号支付
     *
     * @param code
     * @param request
     * @param total_fee
     * @return
     */
    @RequestMapping("/wx/guahaoPay")
    @ResponseBody
    public Map<String, Object> guahaoPay(@RequestParam String code, HttpServletRequest request, @RequestParam String total_fee) {
        String spbill_create_ip = IpUtil.getIpAddr(request);
        String string = wxLoginUtil.Get("https://api.weixin.qq.com/sns/jscode2session?appid=wx697ed96969c6707f&secret=9f1cc13b4ecbc55ae5c9bd0285ddd8b8&js_code=" + code + "&grant_type=authorization_code");
        JSONObject jsonObject = JSONObject.fromObject(string);
        String openid = jsonObject.getString("openid");
        return guahaoPayUtil.prePay(openid, request, total_fee);
    }

    /**
     * 医院版挂号支付成功回调
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/wx/guahaoPaySuccess")
    @ResponseBody
    public void guahaoPaySuccess(HttpServletRequest request, HttpServletResponse response) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        //sb为微信返回的xml
        String notityXml = sb.toString();
        String resXml = "";
        System.out.println("接收到的报文：" + notityXml);
        Map map = PayUtil.doXMLParse(notityXml);
        String returnSign = (String) map.get("sign");
        String returnCode = (String) map.get("return_code");


        //sign不参与签名
        map.remove("sign");
        if ("SUCCESS".equals(returnCode)) {
            //验证签名是否正确

            if (PayUtil.sign(PayUtil.createLinkString(map), WxPayConfig.key, "utf-8").toUpperCase().equals(returnSign)) {
                /**此处添加自己的业务逻辑代码start**/
                String endTime = (String) map.get("time_end");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = simpleDateFormat.parse(endTime);
                endTime = simpleDateFormat1.format(date);
                guahaoHistoryService.finishiGuahaoHistory((String) map.get("out_trade_no"), endTime, (String) map.get("appid"), Integer.parseInt((String) map.get("total_fee")));
                /**此处添加自己的业务逻辑代码end**/
                //通知微信服务器已经支付成功
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
            } else {

            }

        } else {

            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        System.out.println(resXml);
        System.out.println("微信支付回调数据结束");


        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }

    @RequestMapping("/wx/addGuahaoHistory")
    @ResponseBody
    public JSONObject addGuahaoHistory(String out_trade_no, @RequestParam String openId, @RequestParam String name, String idCard, @RequestParam String phoneNumber, @RequestParam String guahaoDate, String caseCard, @RequestParam String moneyNum, @RequestParam Integer masterId) {
        Jedis jedis = new Jedis("localhost");
        openId = jedis.get(openId);
        return guahaoHistoryService.addGuahaoHistory(out_trade_no, openId, name, idCard, phoneNumber, guahaoDate, caseCard, moneyNum, masterId);
    }

    @RequestMapping("/wx/findGuahaoHistory")
    @ResponseBody
    public JSONArray findGuahaoHistory(@RequestParam String openId) {
        Jedis jedis = new Jedis("localhost");
        openId = jedis.get(openId);
        return guahaoHistoryService.findGuahaoHistory(openId);
    }

    /**
     * 法律预约支付
     *
     * @param code
     * @param request
     * @param total_fee
     * @return
     */
    @RequestMapping("/wx/falvGuahaoPay")
    @ResponseBody
    public Map<String, Object> falvGuahaoPay(@RequestParam String code, HttpServletRequest request, @RequestParam String total_fee) {
        String spbill_create_ip = IpUtil.getIpAddr(request);
        String string = wxLoginUtil.Get("https://api.weixin.qq.com/sns/jscode2session?appid=wxeebd2de131ff2f5f&secret=58ea4ec32afb62696d8782554e78ee33&js_code=" + code + "&grant_type=authorization_code");
        JSONObject jsonObject = JSONObject.fromObject(string);
        String openid = jsonObject.getString("openid");
        return falvGuahaoPayUtil.prePay(openid, request, total_fee);
    }

    /**
     * 法律版预约成功回调
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/wx/falvGuahaoPaySuccess")
    @ResponseBody
    public void falvGuahaoPaySuccess(HttpServletRequest request, HttpServletResponse response) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        //sb为微信返回的xml
        String notityXml = sb.toString();
        String resXml = "";
        System.out.println("接收到的报文：" + notityXml);
        Map map = PayUtil.doXMLParse(notityXml);
        String returnSign = (String) map.get("sign");
        String returnCode = (String) map.get("return_code");


        //sign不参与签名
        map.remove("sign");
        if ("SUCCESS".equals(returnCode)) {
            //验证签名是否正确

            if (PayUtil.sign(PayUtil.createLinkString(map), FalvAskPayConfig.key, "utf-8").toUpperCase().equals(returnSign)) {
                /**此处添加自己的业务逻辑代码start**/
                String endTime = (String) map.get("time_end");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = simpleDateFormat.parse(endTime);
                endTime = simpleDateFormat1.format(date);
                guahaoHistoryService.finishiGuahaoHistory((String) map.get("out_trade_no"), endTime, (String) map.get("appid"), Integer.parseInt((String) map.get("total_fee")));
                /**此处添加自己的业务逻辑代码end**/
                //通知微信服务器已经支付成功
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
            } else {

            }

        } else {

            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        System.out.println(resXml);
        System.out.println("微信支付回调数据结束");


        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }
}
